from django.shortcuts import render,get_object_or_404,redirect
from django.http import HttpResponse,JsonResponse,HttpResponseRedirect
from .models import Detail,Content,Modification
from home.models import Udetail
from django.urls import reverse
from django.db.models import Q
import json
# Create your views here.
def index(request, category):
    usr = request.COOKIES.get('usr')
    if not usr:
        return render(request, 'login.html')
    if category == '':
        category == 'library'
    category = get_object_or_404(Detail, name=category)
    res = category.content_set.filter(status=1)

    name = Udetail.objects.get(sno = usr).name

    return render(request, 'message/index.html', {'res':res, 'category':category.Cid, 'detail':category.name, 'name':name})

def cancel(request):
    response = redirect(reverse('home:index'))
    response.delete_cookie('usr')
    return response

def highlight(content, msg):
    index = (content).find(str(msg))
    length = len(str(msg))
    if index == -1 or msg == "":
        return content
    else:
        return content[0:index] + "<mark>" + str(msg) + "</mark>" + content[index+length:]

def ajax(request):
    category = request.POST.get('category','123')
    msg = request.POST.get('msg')
    category = get_object_or_404(Detail, name=category)
    id = category.id
    res = Content.objects.filter(Did_id=id,status=1).filter(Q(user__contains=msg) | Q(title__contains=msg) | Q(text__contains=msg))
    data = []
    data2 = {}
    for item in res:
        # try:
        # item.title = str(item.title)
        title = highlight(item.title, msg)
        user = highlight(item.user, msg)
        text = highlight(item.text, msg)
        data.append({'id':item.id,'user':user, 'time':item.time, 'title':title, 'text':text})
        # data.append(item)
        data2[item.id] = {'id':item.id,'user':item.user, 'time':str(item.time), 'title':item.title, 'text':item.text}
    data = {'data':data}
    return JsonResponse(data)
    # return json.dumps(data)
    # res = {'status':'ok'}
    # return JsonResponse(res)

def add(request):
    title = request.POST.get('title')
    text = request.POST.get('text')
    name = request.POST.get('name')
    category = request.POST.get('Dname')
    category = Detail.objects.get(name = category)
    Did_id = category.id
    dict = {'user':name, 'title':title, 'text':text, 'status':0, 'Did_id':Did_id}
    Content.objects.create(**dict)
    return HttpResponseRedirect('/message/'+category.name)

def modification(request):
    Cid = request.POST.get('id')
    text = request.POST.get('text')
    dict = {'text':text, 'Cid':Cid}
    category = request.POST.get('category')
    Modification.objects.create(**dict)
    return HttpResponseRedirect('/message/' + category)
